import {Component, OnInit} from '@angular/core';
import {BladeContainerBase} from '../../../../../shared/blade/blade-container-base';
import {TreeModule, TreeNode} from 'primeng/primeng';
import {Blade} from '../../../../../shared/blade/blade.model';
import {Command} from '../../../../../shared/toolbar.service';
import {BladeData} from '../../../../../shared/blade/blade-data';
import {Observable} from 'rxjs/Observable';
import {List} from 'linqts';
import {MenuAccess} from '../../../../../entity/menu_access.model';
import {Menu} from '../../../../../entity/menu.model';
import {MenuShortcut} from '../../../../../entity/menu_shortcut.model';
import {MenuAccessService} from '../../../../../service/menu_access.service';
import {MenuShortcutService} from '../../../../../service/menu_shortcut.service';
import {MenuService} from '../../../../../service/menu.service';
import {Role} from '../../../../../entity/role.model';
// import { PermissionListComponent } from "../../permission/permission-list/permission-list.component";
import {MenuAccessEditComponent} from '../../menu-access/menu-access-edit/menu-access-edit.component';
import {RolePermissionListComponent} from '../../role-permission/role-permission-list/role-permission-list.component';
import {MenuShortcutListComponent} from '../../menu-shortcut/menu-shortcut-list/menu-shortcut-list.component';

@Component({
  selector: 'app-menu-access-list',
  templateUrl: './menu-access-list.component.html',
  styleUrls: ['./menu-access-list.component.css']
})
export class MenuAccessListComponent extends BladeContainerBase<MenuAccess> {


  /**
   * 根节点
   *
   * @private
   * @type {Menu}
   * @memberof MenuListComponent
   */
  private rootMenu: Menu = new Menu(0, 'Root', '', '', '', 1, null, 0, []);
  /**
   * 所有节点
   *
   * @type {TreeNode[]}
   * @memberof MenuListComponent
   */
  public files: TreeNode[] = [];

  /**
   * 菜单权限集合
   *
   * @private
   * @type {MenuAccess[]}
   * @memberof MenuAccessListComponent
   */
  private menuAccess: MenuAccess[] = [];

  /**
   * 所有菜单
   *
   * @private
   * @type {Menu[]}
   * @memberof MenuAccessListComponent
   */
  private menus: Menu[] = [];
  private original: Menu[] = [];

  /**
   * 角色菜单权限集合
   *
   * @private
   * @type {Menu[]}
   * @memberof MenuAccessListComponent
   */
  private roleMenus: Menu[] = [];


  /**
   * 固定菜单集合
   *
   * @private
   * @type {MenuShortcut[]}
   * @memberof MenuAccessListComponent
   */
  private menuShortcuts: MenuShortcut[] = [];

  public currentMenu: Menu;

  constructor(
    private menuAccessService: MenuAccessService,
    private menuShortcutService: MenuShortcutService,
    private menuService: MenuService,
  ) {
    super();
    this.commands = [
      new Command('edit', '编辑权限', 'fa fa-edit', 'menu:update', blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
    ];
  }


  /**
   * 初始化数据
   *
   * @returns {(any | Observable<any> | Promise<any>)}
   * @memberof MenuAccessListComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    let getMenuAccess = this.menuAccessService.getMenuAccessByroleId(this.parentEntity.currentEntity.roleId);
    let getMenus = this.menuService.getMenus()
    let getMenuShortCuts = this.menuShortcutService.getMenuShortCutsByroleId(this.parentEntity.currentEntity.roleId);
    Promise.all([getMenuAccess, getMenus, getMenuShortCuts])
      .then(res => {
        if (res[0]) {
          this.menuAccess = [...res[0]];
          // console.log(this.menuAccess)
        }
        ;
        if (res[1]) {
          this.menus = [...res[1]];
        }
        ;
        if (res[2]) {
          this.menuShortcuts = [...res[2]];
        }
        ;
        //----------------
        let menuAccessIds = [];
        this.menuAccess.forEach(a => {
          menuAccessIds.push(a.menuId);
          menuAccessIds = Array.from(new Set(menuAccessIds));//去重
        })
        // console.log(this.menus)
        this.menus.forEach(m => {
          if (menuAccessIds.find(a => a != m.menuId) && m.menuLevel != 1) {
            m.isShow = false;
          }
        })
        //----------------
        //是否显示

        this.menuAccess.forEach(menuAccess => {
          this.menus.forEach(menu => {
            menu.unMenuShortCuts = false;
            if (menuAccess.menuId == menu.menuId) {
              menu.isShow = menuAccess.unVisible;
            }
          })
        })

        //设置固定菜单
        this.menuShortcuts.forEach(menuShortcut => {
          this.menus.forEach(menu => {
            if (menuShortcut.menuId == menu.menuId) {
              menu.unMenuShortCuts = true;
            }
          })
        })

        this.original = [this.rootMenu];
        this.original.push(...this.menus);

        this.files = [];
        let level: number = 1;
        let firstMenus = this.original.filter(o => o.parentId == 0);
        if (firstMenus != null) {
          firstMenus = new List(firstMenus).OrderBy(o => o.menuSeq).ToArray();
          firstMenus.forEach(menu => {
            menu.menuLevel = level;
            let treeNode: TreeNode = {};
            treeNode.data = menu;
            this.files.push(treeNode);
            this.initChildMenu(menu, treeNode);
          });
        }
        //
        this.files.forEach(file => {
          if (file.children !== undefined) {
            if (file.children.find(item => item.data.isShow == true)) {
              file.data.isShow = true;
            } else {
              file.data.isShow = false;
            }
          }

        })

        //
        this.menus = this.original;
        this.currentMenu = this.menus[1];
        if (this.parentEntity.isShowChild) {
          // this.showPermissionListBlade(this.parentEntity.currentEntity)
          this.showMenuShortcutListBlade(this.parentEntity.currentEntity)
        }

      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  /**
   * 递归初始化子菜单
   *
   * @param {Menu} menu
   * @param {TreeNode} treeNode
   * @memberof MenuListComponent
   */
  initChildMenu(menu: Menu, treeNode: TreeNode) {
    let childrenMenus = this.original.filter(o => o.parentId == menu.menuId);
    if (childrenMenus != null && childrenMenus.length > 0) {
      let level: number = menu.menuLevel + 1;
      let list = new List(childrenMenus);
      let childrenTemp = list.OrderBy(o => o.menuSeq).ToArray();
      menu.children = childrenTemp;
      menu.children.forEach(childrenMenu => {
        childrenMenu.menuLevel = level;
        let childernTreeNode: TreeNode = {};
        childernTreeNode.data = childrenMenu;
        if (!treeNode.children) {
          treeNode.children = [];
        }
        treeNode.children.push(childernTreeNode);
        //递归
        this.initChildMenu(childrenMenu, childernTreeNode);
      });
    }
  }


  public onNodeSelect(event: any, file) {
    let menu = file.data;
    menu.isChecked = !menu.isChecked;
    this.currentMenu = menu;
    //  console.log(this.currentMenu)
    event.stopPropagation();
    this.showMenuShortcutListBlade(this.parentEntity.currentEntity)
  }

  /**
   * 单选
   *
   * @param {any} event
   * @param {any} key
   *
   * @memberof
   */
  onItemCheack(event: HTMLInputElement, menu: Menu) {
    this.setChildrenChecked(menu, event.checked);
    this.setParenChecked(menu);
  }

  /**
   * 设置子菜单是否选中
   *
   * @param {Menu} menu
   * @param {boolean} isChecked
   * @memberof MenuListComponent
   */
  setChildrenChecked(menu: Menu, isChecked: boolean) {
    menu.isChecked = isChecked;
    if (menu.children && menu.children.length) {
      menu.children.forEach(childMenu => {
        this.setChildrenChecked(childMenu, isChecked);
      });
    }
  }

  /**
   * 设置父菜单是否选中
   *
   * @param {Menu} menu
   * @memberof MenuListComponent
   */
  setParenChecked(menu: Menu) {
    let parenMenu = this.menus.find(o => o.menuId == menu.parentId);
    if (parenMenu != null) {
      let isCheckedCount = parenMenu.children.filter(o => o.isChecked).length;
      if (isCheckedCount == parenMenu.children.length) {
        parenMenu.isChecked = true;
      }
      else {
        parenMenu.isChecked = false;
      }
      this.setParenChecked(parenMenu);
    }
  }


  /**
   *显示操作权限
   *
   * @param {Role} selectedRole
   * @memberof MenuAccessListComponent
   */
  showPermissionListBlade(selectedRole: Role) {
    if (this.parentEntity.currentEntity != undefined) {
      this.currentBlade.bladeService.closeChildrenBlade;
      let data: BladeData = new BladeData();
      data.id = 'permissionList';
      data.title = selectedRole.roleName;
      data.subtitle = '操作权限';
      data.isClosingDisabled = false;
      let permissionListBlade = this.bladeService.createBlade(RolePermissionListComponent, data, false, null, {
        currentEntity: this.parentEntity.currentEntity,
        isShowChild: this.parentEntity.isShowChild
      });
      this.bladeService.showBlade(permissionListBlade, this.currentBlade)
    }
  }

  showMenuShortcutListBlade(selectedRole: Role) {
    if (this.parentEntity.currentEntity != undefined) {
      this.currentBlade.bladeService.closeChildrenBlade;
      let data: BladeData = new BladeData();
      data.id = 'menuShortcutList';
      data.title = selectedRole.roleName;
      data.subtitle = '固定菜单';
      data.isClosingDisabled = false;
      let menuShortcutListBlade = this.bladeService.createBlade(MenuShortcutListComponent, data, false,

        null, selectedRole);
      this.bladeService.showBlade(menuShortcutListBlade, this.currentBlade)
    }
  }


  /**
   * 编辑权限
   *
   * @param {Blade} blend
   * @memberof MenuAccessListComponent
   */
  exeEdit(blend: Blade): void {

    if (this.currentMenu != undefined) {
      this.bladeService.closeChildrenBlade
      let data: BladeData = new BladeData();
      data.id = 'menuAccessEdit';
      data.title = this.currentMenu.menuName;
      data.subtitle = '菜单权限';
      // console.log(this.currentMenu)
      let editKeyBlade = this.bladeService.createBlade(MenuAccessEditComponent, data, false, this.currentMenu, this.parentEntity.currentEntity);
      this.currentBlade.bladeService.showBlade(editKeyBlade, this.currentBlade);
    }
  }

  canExeEdit(blend?: Blade): boolean {
    return this.currentMenu != null;
  }


}


// WEBPACK FOOTER //
// ./src/app/module/admin/role/menu-access/menu-access-list/menu-access-list.component.ts
